import React,{ useContext, useEffect } from 'react'
import { Badge, Menu } from 'antd'
import { Link } from 'react-router-dom'
import { useSelector } from '../../hooks/useSelector'
import { isAuth } from '../../helpers/auth'
import { TotalContext } from '../../anotherStore'
import { itemCount } from '../../helpers/cart'
// import { useSelector } from 'react-redux'
// import { RootState } from '../../store/reducers'

function useAcitve(currentPath:string,path:string):string{
  return currentPath===path?'ant-menu-item-selected':''
}

const Navigation = () => {
  // const router = useSelector<RootState>(state=> state.router)
  const router = useSelector(state=> state.router)
  const pathname = router.location.pathname
  const isHome = useAcitve(pathname,'/')
  const isShop = useAcitve(pathname,'/shop')
  const isSignin = useAcitve(pathname,'/signin')
  const isSignup = useAcitve(pathname,'/signup')
  const isCart = useAcitve(pathname,'/cart')
  const isDashboard = useAcitve(pathname,getDashboard())

  const [count,setCount ] = useContext(TotalContext)
  useEffect(()=>{
    setCount(itemCount())
  })

  function getDashboard():String{
    let url = '/user/dashboard'
    if(isAuth()){
      const { user: { role } } = isAuth()
      if(role===1){
        url = '/admin/dashboard'
      }
    }
    return url
  }

  // ant-menu-item-selected
  return <Menu mode='horizontal' selectable={false}>
    <Menu.Item className={isHome}>
      <Link to="/">首页</Link>
    </Menu.Item>
    <Menu.Item className={isShop}>
      <Link to="/shop">商城</Link>
    </Menu.Item>
    <Menu.Item className={isCart}>
      <Link to="/cart">
        购物车
        <Badge count={ count } offset={ [5,-10] }/>
      </Link>
    </Menu.Item>
    { !isAuth()&&(
      <>
        <Menu.Item className={isSignin}>
          <Link to="/signin">登录</Link>
        </Menu.Item>
        <Menu.Item className={isSignup}>
          <Link to="/signup">注册</Link>
        </Menu.Item>
      </>
    )}
    {
      isAuth()&&(
      <Menu.Item className={isDashboard}>
          <Link to={getDashboard()}>dashboard</Link>
        </Menu.Item>
      )
    }
    
  </Menu>
}

export default Navigation